# -*- coding: utf-8 -*-
"""
A 股形态选股与量化评估系统（优化版 v5：腾讯接口极速版）
========================================================================
- 全面改用腾讯财经接口（qt.gtimg.cn）极速获取股票池，杜绝连接断开
- 统一使用基于脚本当前目录的 SQLite (stock_cache.sqlite3) 本地高速缓存
- 选股与形态评估核心算法保持 100% 原始逻辑
"""

from __future__ import annotations

import argparse
import datetime as dt
import logging
import os
import random
import re
import sqlite3
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, List, Optional, Tuple

import akshare as ak
import numpy as np
import pandas as pd
import requests

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%H:%M:%S",
)
logger = logging.getLogger("StockPicker")

# =========================================================
#  可调参数区 (Strategy Configuration)
# =========================================================

DATA_DAYS = 730                      # 拉取日历天数 (覆盖近2年)[cite: 2]
MIN_LISTING_BARS = 180              # 上市至少 180 个交易日（过滤次新）[cite: 2]
POOL_PREFIX = ("60", "00", "30", "68") # 排除北交所，保留主板/双创[cite: 2]
EXCLUDE_KEYWORDS = ("ST", "退")[cite: 2]
MIN_PRICE = 2.0[cite: 2]

# 均线系统
MA_FAST, MA_MID, MA_SLOW = 20, 50, 200[cite: 2]
SLOPE_FAST_BARS = 5[cite: 2]
SLOPE_SLOW_BARS = 20[cite: 2]
BASE_FLOOR_RATIO = 0.93             # 近 10 日最低价 >= MA20 * 0.93[cite: 2]
CLOSE_MIN_RATIO = 0.97              # 现价 >= MA20 * 0.97[cite: 2]
MAX_BIAS_MA20 = 0.30                # 现价偏离 MA20 最大 30%[cite: 2]

# 平台与突破
BASE_WIN = 120                      # 平台回看最长窗口[cite: 2]
BASE_MIN_BARS = 60                  # 平台最少 K 线数 (约3个月)[cite: 2]
BASE_MAX_WIDTH = 0.55               # 平台箱体振幅 (高/低 - 1)[cite: 2]
BASE_NET_LO, BASE_NET_HI = -0.30, 0.60[cite: 2]
LOOKBACK_HIGH = 60                  # 创 N 日新高[cite: 2]
VOL_SURGE_MIN = 1.5                 # 突破日放量 >= 1.5 倍 20日均量[cite: 2]
BREAK_MIN_CHG = 0.04                # 突破日中阳起爆涨幅 >= 4%[cite: 2]
POST_MIN_BARS = 1                   # 突破发生至少 1 天以上[cite: 2]
POST_MAX_BARS = 60                 # 突破后最长跟踪窗口，超过视为旧突破硬淘汰[cite: 2]
MAX_GAIN_SINCE = 0.80              # 突破后累计涨幅上限，超过视为透支硬淘汰[cite: 2]

# 运行参数
FETCH_WORKERS = 6                   # 并发拉取线程数[cite: 2]
MAX_RATE_PER_SEC = 10.0             # 全局最高 QPS 限流[cite: 2]
MIN_SCORE = 70[cite: 2]
CACHE_DB_NAME = "stock_cache.sqlite3"[cite: 2]
OUTPUT_SUBDIR = "选股结果"[cite: 2]


# =========================================================
#  限流器与安全网络 (Rate Limiter & Resilient Network)
# =========================================================

class TokenBucketLimiter:
    """平滑令牌桶限流器，防止打爆行情接口触发封禁。"""[cite: 2]
    def __init__(self, rate: float):
        self.rate = rate[cite: 2]
        self.capacity = max(1.0, rate)[cite: 2]
        self.tokens = self.capacity[cite: 2]
        self.last_time = time.monotonic()[cite: 2]
        self.lock = threading.Lock()[cite: 2]

    def acquire(self):
        with self.lock:
            now = time.monotonic()[cite: 2]
            elapsed = now - self.last_time[cite: 2]
            self.last_time = now[cite: 2]
            self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)[cite: 2]
            if self.tokens < 1.0:[cite: 2]
                wait_time = (1.0 - self.tokens) / self.rate[cite: 2]
                time.sleep(wait_time)[cite: 2]
                self.tokens = 0.0[cite: 2]
            else:
                self.tokens -= 1.0[cite: 2]

LIMITER = TokenBucketLimiter(MAX_RATE_PER_SEC)[cite: 2]
NETWORK_AVAILABLE = True[cite: 2]


def probe_network(timeout: float = 3.5) -> bool:
    """快速探测腾讯行情接口是否可达。"""
    global NETWORK_AVAILABLE
    urls = [
        "http://qt.gtimg.cn/q=sh600519",
        "http://qt.gtimg.cn/q=sz000001",
    ]
    for u in urls:
        try:
            r = requests.get(u, timeout=timeout, proxies={"http": None, "https": None})
            if r.status_code == 200 and len(r.text) > 0:
                NETWORK_AVAILABLE = True
                print("✓ 网络探测: 腾讯行情接口可达，将在线更新/拉取数据")
                return True
        except Exception:
            continue
    NETWORK_AVAILABLE = False
    print("✗ 网络探测: 行情接口不可达，将尝试使用本地 SQLite 缓存离线运行")
    return False


# =========================================================
#  SQLite 集中式高性能缓存引擎
# =========================================================

class SQLiteStorage:
    def __init__(self, db_path: str):
        self.db_path = db_path[cite: 2]
        self._local = threading.local()[cite: 2]
        self._init_db()[cite: 2]

    def _get_conn(self) -> sqlite3.Connection:
        if not hasattr(self._local, "conn") or self._local.conn is None:[cite: 2]
            conn = sqlite3.connect(self.db_path, timeout=30.0)[cite: 2]
            conn.execute("PRAGMA journal_mode = WAL")[cite: 2]
            conn.execute("PRAGMA synchronous = NORMAL")[cite: 2]
            self._local.conn = conn[cite: 2]
        return self._local.conn[cite: 2]

    def _init_db(self):
        conn = sqlite3.connect(self.db_path)[cite: 2]
        with conn:
            conn.execute("""
                CREATE TABLE IF NOT EXISTS stock_pool_meta (
                    symbol TEXT PRIMARY KEY,
                    name TEXT,
                    updated_at TEXT
                )
            """)[cite: 2]
            conn.execute("""
                CREATE TABLE IF NOT EXISTS kline_cache (
                    symbol TEXT,
                    trade_date TEXT,
                    open REAL,
                    close REAL,
                    high REAL,
                    low REAL,
                    volume REAL,
                    updated_at TEXT,
                    PRIMARY KEY(symbol, trade_date)
                )
            """)[cite: 2]
            conn.execute("CREATE INDEX IF NOT EXISTS idx_sym_date ON kline_cache(symbol, trade_date)")[cite: 2]
        conn.close()[cite: 2]

    def get_cached_pool(self) -> pd.DataFrame:
        conn = self._get_conn()[cite: 2]
        df = pd.read_sql_query("SELECT symbol as 代码, name as 名称 FROM stock_pool_meta", conn)[cite: 2]
        return df[cite: 2]

    def save_cached_pool(self, df: pd.DataFrame):
        if df.empty:[cite: 2]
            return
        conn = self._get_conn()[cite: 2]
        now_str = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")[cite: 2]
        records = [(str(row.代码).zfill(6), str(row.名称), now_str) for row in df.itertuples()][cite: 2]
        with conn:
            conn.executemany("INSERT OR REPLACE INTO stock_pool_meta (symbol, name, updated_at) VALUES (?, ?, ?)", records)[cite: 2]

    def get_kline(self, symbol: str, start_date: str) -> Optional[pd.DataFrame]:
        conn = self._get_conn()[cite: 2]
        query = """
            SELECT trade_date as 日期, open as 开盘, close as 收盘,
                   high as 最高, low as 最低, volume as 成交量
            FROM kline_cache
            WHERE symbol = ? AND trade_date >= ?
            ORDER BY trade_date ASC
        """[cite: 2]
        df = pd.read_sql_query(query, conn, params=(symbol, start_date))[cite: 2]
        if df.empty or len(df) < MIN_LISTING_BARS:[cite: 2]
            return None[cite: 2]
        df["日期"] = pd.to_datetime(df["日期"])[cite: 2]
        return df[cite: 2]

    def save_kline(self, symbol: str, df: pd.DataFrame):
        if df.empty:[cite: 2]
            return
        conn = self._get_conn()[cite: 2]
        now_str = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")[cite: 2]
        records = [][cite: 2]
        for row in df.itertuples(index=False):[cite: 2]
            d_str = pd.to_datetime(row.日期).strftime("%Y%m%d")[cite: 2]
            records.append((
                symbol, d_str,
                float(getattr(row, "开盘", row.收盘)),
                float(row.收盘), float(row.最高), float(row.最低),
                float(row.成交量), now_str
            ))[cite: 2]
        with conn:
            conn.executemany("""
                INSERT OR REPLACE INTO kline_cache
                (symbol, trade_date, open, close, high, low, volume, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            """, records)[cite: 2]


# =========================================================
#  数据层规范与清洗
# =========================================================

def _with_prefix(symbol: str) -> str:
    code = symbol.strip()[cite: 2]
    return ("sh" if code.startswith(("6", "9")) else "sz") + code[cite: 2]


def _norm_df(df: pd.DataFrame) -> pd.DataFrame:
    if df is None or df.empty:[cite: 2]
        return pd.DataFrame()[cite: 2]
    lower = {str(c).lower(): c for c in df.columns}[cite: 2]
    def g(*names):
        for nm in names:[cite: 2]
            if nm in lower:[cite: 2]
                return lower[nm][cite: 2]
        return None[cite: 2]

    dcol = g("日期", "date")[cite: 2]
    if dcol is None:[cite: 2]
        return pd.DataFrame()[cite: 2]

    out = {"日期": pd.to_datetime(df[dcol], errors="coerce")}[cite: 2]
    for target, names in {
        "开盘": ("开盘", "open"),
        "收盘": ("收盘", "close"),
        "最高": ("最高", "high"),
        "最低": ("最低", "low"),
        "成交量": ("成交量", "volume"),
    }.items():[cite: 2]
        col = g(*names)[cite: 2]
        out[target] = pd.to_numeric(df[col], errors="coerce") if col else np.nan[cite: 2]

    res = pd.DataFrame(out).dropna(subset=["日期", "收盘", "最高", "最低"])[cite: 2]
    if "开盘" in res.columns and res["开盘"].isna().any():[cite: 2]
        res["开盘"] = res["开盘"].fillna(res["收盘"])[cite: 2]
    return res.sort_values("日期").drop_duplicates(subset="日期", keep="last").reset_index(drop=True)[cite: 2]


def fetch_stock_daily(symbol: str, storage: SQLiteStorage, use_cache: bool = True) -> pd.DataFrame:
    today_str = dt.date.today().strftime("%Y%m%d")[cite: 2]
    start_str = (dt.date.today() - dt.timedelta(days=DATA_DAYS)).strftime("%Y%m%d")[cite: 2]

    # 1. 本地缓存读取
    cached_df = None[cite: 2]
    if use_cache:[cite: 2]
        cached_df = storage.get_kline(symbol, start_str)[cite: 2]
        if cached_df is not None and not cached_df.empty:[cite: 2]
            if (dt.date.today() - cached_df["日期"].iloc[-1].date()).days <= 3:[cite: 2]
                return cached_df[cite: 2]

    # 2. 在线拉取与重试（优先腾讯 tx 通道）
    errors = [][cite: 2]
    if NETWORK_AVAILABLE:[cite: 2]
        sources = [
            ("tx", lambda: ak.stock_zh_a_hist_tx(symbol=_with_prefix(symbol), start_date=start_str, end_date=today_str, adjust="qfq")),[cite: 2]
            ("sina", lambda: ak.stock_zh_a_daily(symbol=_with_prefix(symbol), start_date=start_str, end_date=today_str, adjust="qfq")),[cite: 2]
            ("em", lambda: ak.stock_zh_a_hist(symbol=symbol, period="daily", start_date=start_str, end_date=today_str, adjust="qfq")),[cite: 2]
        ]

        for src_name, fetch_fn in sources:[cite: 2]
            for attempt in range(2):[cite: 2]
                LIMITER.acquire()[cite: 2]
                try:
                    raw = fetch_fn()[cite: 2]
                    df = _norm_df(raw)[cite: 2]
                    if not df.empty and len(df) >= MIN_LISTING_BARS:[cite: 2]
                        if use_cache:[cite: 2]
                            storage.save_kline(symbol, df)[cite: 2]
                        return df[cite: 2]
                except Exception as e:
                    errors.append(f"{src_name}:{str(e)[:30]}")[cite: 2]
                    time.sleep(0.3 * (attempt + 1) + random.random() * 0.2)[cite: 2]

    # 3. 离线降级
    if cached_df is not None and not cached_df.empty:[cite: 2]
        return cached_df[cite: 2]

    raise RuntimeError(" | ".join(errors) if errors else "无有效日线数据返回")[cite: 2]


# =========================================================
#  形态计算纯函数模块 (向量化评估)
# =========================================================

def evaluate_technical_pattern(symbol: str, name: str, df: pd.DataFrame) -> Tuple[Optional[Dict], Optional[str]]:
    n = len(df)[cite: 2]
    if n < MIN_LISTING_BARS:[cite: 2]
        return None, f"上市交易日不足{MIN_LISTING_BARS}天(排除次新)"[cite: 2]

    c = df["收盘"].to_numpy(dtype=float)[cite: 2]
    o = df["开盘"].to_numpy(dtype=float)[cite: 2]
    h = df["最高"].to_numpy(dtype=float)[cite: 2]
    l = df["最低"].to_numpy(dtype=float)[cite: 2]
    v = df["成交量"].to_numpy(dtype=float)[cite: 2]

    s_close = pd.Series(c)[cite: 2]
    ma20 = s_close.rolling(MA_FAST).mean().to_numpy()[cite: 2]
    ma50 = s_close.rolling(MA_MID).mean().to_numpy()[cite: 2]
    ma200 = s_close.rolling(MA_SLOW).mean().to_numpy()[cite: 2]
    vma20 = pd.Series(v).shift(1).rolling(MA_FAST).mean().to_numpy()[cite: 2]
    roll_max60 = pd.Series(h).shift(1).rolling(LOOKBACK_HIGH).max().to_numpy()[cite: 2]

    # 1. 均线与价格硬门槛过滤
    if np.isnan(ma200[-1]) or np.isnan(ma200[-1 - SLOPE_SLOW_BARS]):[cite: 2]
        return None, "MA200有效数据不足"[cite: 2]
    if not (ma20[-1] > ma50[-1] > ma200[-1]):[cite: 2]
        return None, "均线未形成多头排列"[cite: 2]
    if ma20[-1] <= ma20[-1 - SLOPE_FAST_BARS]:[cite: 2]
        return None, "MA20短期斜率未向上"[cite: 2]
    bias20 = c[-1] / ma20[-1] - 1.0[cite: 2]
    if bias20 > MAX_BIAS_MA20:[cite: 2]
        return None, f"乖离过大({bias20*100:.1f}%), 谨防追顶"[cite: 2]
    if c[-1] < ma20[-1] * CLOSE_MIN_RATIO:[cite: 2]
        return None, "现价已跌破MA20"[cite: 2]
    floor10 = float(np.min(l[-10:] / ma20[-10:]))[cite: 2]
    if floor10 < BASE_FLOOR_RATIO:[cite: 2]
        return None, "近10日破MA20支撑"[cite: 2]

    # 2. 均线打分 (总分 30)
    score_A = 8[cite: 2]
    ma200_up = ma200[-1] > ma200[-1 - SLOPE_SLOW_BARS][cite: 2]
    ma20_slope_val = (ma20[-1] - ma20[-1 - SLOPE_FAST_BARS]) / ma20[-1 - SLOPE_FAST_BARS][cite: 2]
    score_A += 6 if (ma200_up and ma20_slope_val > 0.005) else (4 if (ma200_up or ma20_slope_val > 0.005) else 2)[cite: 2]
    score_A += 4 if (c[-1] >= ma20[-1] and c[-1] >= ma50[-1]) else 2[cite: 2]

    ride_ratio = float(np.mean(l[-20:] / ma20[-20:] >= 0.95))[cite: 2]
    score_A += 7 if ride_ratio >= 0.95 else (6 if ride_ratio >= 0.85 else (5 if ride_ratio >= 0.70 else 3))[cite: 2]

    d_bias = abs(bias20)[cite: 2]
    score_A += 5 if d_bias <= 0.05 else (4 if d_bias <= 0.10 else (2 if d_bias <= 0.18 else 0))[cite: 2]

    # 3. 突破信号与吸筹平台检测 (总分 45)
    r = np.zeros(n)[cite: 2]
    r[1:] = c[1:] / c[:-1] - 1.0[cite: 2]

    valid_break_mask = (
        (~np.isnan(vma20)) & (vma20 > 0) &
        (~np.isnan(ma50)) & (~np.isnan(ma200)) &
        (c > roll_max60) &
        (v >= VOL_SURGE_MIN * vma20) &
        (c > ma50) & (c > ma200) &
        (r >= BREAK_MIN_CHG) &
        (c > o) &
        (np.isfinite(o)) & (o > 0)
    )[cite: 2]
    candidate_indices = np.where(valid_break_mask)[0][cite: 2]
    candidate_indices = [
        i for i in candidate_indices
        if i >= BASE_MIN_BARS and (n - 1 - i) >= POST_MIN_BARS
    ][cite: 2]

    if not candidate_indices:[cite: 2]
        return None, "未发现放量突破信号"[cite: 2]

    chosen_e = None[cite: 2]
    for e_candidate in reversed(candidate_indices):[cite: 2]
        b0 = max(0, e_candidate - BASE_WIN)[cite: 2]
        hi_box = h[b0:e_candidate].max()[cite: 2]
        lo_box = l[b0:e_candidate].min()[cite: 2]
        if lo_box <= 0 or (hi_box / lo_box - 1.0) > BASE_MAX_WIDTH:[cite: 2]
            continue
        net_box = c[e_candidate - 1] / c[b0] - 1.0[cite: 2]
        if not (BASE_NET_LO <= net_box <= BASE_NET_HI):[cite: 2]
            continue
        if c[e_candidate] < hi_box * 0.98:[cite: 2]
            continue
        chosen_e = e_candidate[cite: 2]
        break

    if chosen_e is None:[cite: 2]
        return None, "突破事件存在但前期吸筹平台不规范"[cite: 2]

    e = chosen_e[cite: 2]
    post_bars = n - 1 - e[cite: 2]
    gain_since = c[-1] / c[e] - 1.0[cite: 2]

    if post_bars > POST_MAX_BARS:[cite: 2]
        return None, f"突破已过去{post_bars}日(>{POST_MAX_BARS}日上限, 视为旧突破)"[cite: 2]
    if gain_since > MAX_GAIN_SINCE:[cite: 2]
        return None, f"突破后涨幅{gain_since*100:.0f}%已透支(防接盘)"[cite: 2]

    b0 = max(0, e - BASE_WIN)[cite: 2]
    bars = e - b0[cite: 2]
    width = h[b0:e].max() / l[b0:e].min() - 1.0[cite: 2]
    box_hi = h[b0:e].max()[cite: 2]
    vol_surge = v[e] / vma20[e][cite: 2]

    b1 = (5 if bars >= 120 else 4 if bars >= 90 else 3) + (5 if width <= 0.35 else 4 if width <= 0.45 else 3)[cite: 2]
    margin = c[e] / box_hi - 1.0[cite: 2]
    b2 = 2[cite: 2]
    b2 += 2 if margin >= 0.02 else (1 if margin >= 0.005 else 0)[cite: 2]
    b2 += 2 if vol_surge >= 2.0 else (1 if vol_surge >= 1.5 else 0)[cite: 2]

    limit_up = 0.195 if symbol.startswith(("300", "301", "688")) else 0.095[cite: 2]
    b3 = 5 if r[e] >= limit_up - 0.005 else (4 if r[e] >= 0.05 else 3)[cite: 2]

    if post_bars <= 5:[cite: 2]
        b4 = 10 if c[-1] >= c[e] * 0.98 else 6[cite: 2]
        b5 = 4[cite: 2]
        stage_desc = "刚突破起爆"[cite: 2]
    else:
        post = np.arange(e + 1, n)[cite: 2]
        above_frac = float(np.mean(c[post] >= ma20[post]))[cite: 2]
        if above_frac < 0.50:[cite: 2]
            return None, "突破后跌破MA20过频"[cite: 2]
        b4 = (6 if above_frac >= 0.80 else 4) + (6 if float(np.min(l[post] / ma20[post])) >= 0.94 else 3)[cite: 2]
        b5 = 4 if gain_since >= 0.05 else 2[cite: 2]
        stage_desc = "回踩蓄势/主升"[cite: 2]

    b6 = 5 if gain_since < 0.50 else (4 if gain_since < 1.00 else 2)[cite: 2]
    score_B = b1 + b2 + b3 + b4 + b5 + b6[cite: 2]

    # 4. 量价配合分析 (总分 25)
    c1 = 8 if vol_surge >= 2.2 else (6 if vol_surge >= 1.6 else 4)[cite: 2]
    c2 = 4 if v[e:e + min(3, n - e)].mean() / vma20[e] >= 1.3 else 2[cite: 2]

    if post_bars > 1:[cite: 2]
        ret_post = np.diff(c[e:])[cite: 2]
        post_vol = v[e + 1:][cite: 2]
        up_vol = post_vol[ret_post >= 0][cite: 2]
        dn_vol = post_vol[ret_post < 0][cite: 2]
        if len(up_vol) > 0 and len(dn_vol) > 0 and up_vol.mean() > 0:[cite: 2]
            vol_ratio = float(dn_vol.mean() / up_vol.mean())[cite: 2]
            c3 = 7 if vol_ratio <= 0.65 else (5 if vol_ratio <= 0.85 else 3)[cite: 2]
        else:
            c3 = 4[cite: 2]
    else:
        c3 = 5[cite: 2]

    recent_idx = range(max(0, n - 5), n)[cite: 2]
    c4_ok = all(np.isfinite(vma20[i]) and v[i] <= 3.5 * vma20[i] for i in recent_idx)[cite: 2]
    c4 = 4 if c4_ok else 1[cite: 2]
    score_C = c1 + c2 + c3 + c4[cite: 2]

    total_score = min(100, score_A + score_B + score_C)[cite: 2]
    latest_date = df["日期"].iloc[-1].strftime("%Y-%m-%d")[cite: 2]

    return {
        "代码": symbol,
        "名称": name,
        "阶段": stage_desc,
        "数据日期": latest_date,
        "收盘": round(float(c[-1]), 2),
        "MA20": round(float(ma20[-1]), 2),
        "MA50": round(float(ma50[-1]), 2),
        "MA200": round(float(ma200[-1]), 2),
        "综合评分": int(total_score),
        "均线分": score_A,
        "形态分": score_B,
        "量价分": score_C,
        "乖离MA20%": round(bias20 * 100, 1),
        "突破日期": df["日期"].iloc[e].strftime("%Y-%m-%d"),
        "突破后交易日": int(post_bars),
        "突破日涨幅%": round(r[e] * 100, 1),
        "突破量比": round(float(vol_surge), 1),
        "突破后涨幅%": round(gain_since * 100, 1),
        "平台振幅%": round(width * 100, 1),
        "平台K线数": int(bars),
    }, None[cite: 2]


# =========================================================
#  调度工作流
# =========================================================

class StockScanner:
    def __init__(self, args, storage: SQLiteStorage):
        self.args = args[cite: 2]
        self.storage = storage[cite: 2]
        self.lock = threading.Lock()[cite: 2]
        self.analyzed_count = 0[cite: 2]
        self.error_count = 0[cite: 2]
        self.matched_rows: List[Dict] = [][cite: 2]
        self.skip_reasons: Dict[str, int] = {}[cite: 2]

    def _process_one(self, code: str, name: str):
        try:
            df = fetch_stock_daily(code, self.storage, use_cache=not self.args.no_cache)[cite: 2]
        except Exception as err:
            with self.lock:
                self.error_count += 1[cite: 2]
                reason = f"网络/数据异常: {str(err)[:40]}"[cite: 2]
                self.skip_reasons[reason] = self.skip_reasons.get(reason, 0) + 1[cite: 2]
            return

        detail, reason = evaluate_technical_pattern(code, name, df)[cite: 2]

        with self.lock:
            self.analyzed_count += 1[cite: 2]
            cur_done = self.analyzed_count[cite: 2]
            if detail is not None:
                if detail["综合评分"] >= self.args.min_score:[cite: 2]
                    self.matched_rows.append(detail)[cite: 2]
                    print(f"  ★ [{detail['阶段']}] {code} {name:<6} "
                          f"评分: {detail['综合评分']} (均线{detail['均线分']}/形态{detail['形态分']}/量价{detail['量价分']}) "
                          f"突破后天数: {detail['突破后交易日']}", flush=True)[cite: 2]
            elif reason:
                self.skip_reasons[reason] = self.skip_reasons.get(reason, 0) + 1[cite: 2]

            if cur_done % 100 == 0:[cite: 2]
                print(f"  >> 扫描进度: {cur_done} 只已完成...", flush=True)[cite: 2]

    def run(self, pool: pd.DataFrame) -> pd.DataFrame:
        items = list(zip(pool["代码"].astype(str), pool["名称"].astype(str)))[cite: 2]
        workers = min(self.args.workers, len(items) or 1)[cite: 2]
        t0 = time.time()[cite: 2]
        print(f"=== 启动形态扫描: 共 {len(items)} 只标的, 并发工作线程: {workers} ===")[cite: 2]

        with ThreadPoolExecutor(max_workers=workers) as executor:[cite: 2]
            futs = [executor.submit(self._process_one, c, n) for c, n in items][cite: 2]
            try:
                for _ in as_completed(futs):[cite: 2]
                    pass
            except KeyboardInterrupt:
                print("\n[中断] 用户手动停止，准备整理已有结果...")[cite: 2]
                executor.shutdown(wait=False, cancel_futures=True)[cite: 2]

        elapsed = time.time() - t0[cite: 2]
        print(f"\n扫描完成! 总耗时: {elapsed:.1f} 秒, 分析: {self.analyzed_count}, 异常: {self.error_count}")[cite: 2]
        return self._summarize()[cite: 2]

    def _summarize(self) -> pd.DataFrame:
        if self.skip_reasons:[cite: 2]
            print("\n主要未通过/拦截原因分布 (TOP 8):")[cite: 2]
            for k, v in sorted(self.skip_reasons.items(), key=lambda x: -x[1])[:8]:[cite: 2]
                print(f"  {v:>5} 只: {k}")[cite: 2]

        if not self.matched_rows:[cite: 2]
            print("\n未筛选出达标股票。")[cite: 2]
            return pd.DataFrame()[cite: 2]

        df_res = pd.DataFrame(self.matched_rows).sort_values(
            by=["综合评分", "突破后涨幅%"], ascending=[False, False]
        ).reset_index(drop=True)[cite: 2]
        return df_res[cite: 2]


# =========================================================
#  腾讯财经接口获取全市场股票池（高稳、高速、轻量）
# =========================================================

def get_stock_pool(codes: Optional[str], limit: Optional[int], storage: SQLiteStorage) -> pd.DataFrame:
    if codes:[cite: 2]
        wanted = [x.strip() for x in codes.split(",") if x.strip()][cite: 2]
        return pd.DataFrame({"代码": wanted, "名称": wanted})[cite: 2]

    # 1. 优先读取本地 SQLite 缓存代码表
    cached_pool = storage.get_cached_pool()[cite: 2]
    if cached_pool is not None and len(cached_pool) >= 1000:[cite: 2]
        print(f"✓ 已秒级命中本地股票池缓存: 共 {len(cached_pool)} 只")[cite: 2]
        if limit and limit > 0:[cite: 2]
            return cached_pool.head(limit)[cite: 2]
        return cached_pool[cite: 2]

    print("首次初始化全市场股票池（使用腾讯财经行情源）...")
    exclude_pat = "|".join([re.escape(k) for k in EXCLUDE_KEYWORDS])[cite: 2]
    pool = pd.DataFrame()

    session = requests.Session()
    session.trust_env = False  # 绕过损坏代理
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/122.0.0.0 Safari/537.36",
        "Referer": "https://gu.qq.com/",
    }

    # 方式 1：腾讯批量行情接口分页扫描（每页 200 条，纯文本极速返回）
    all_rows = []
    markets = [("sh_a", "sh"), ("sz_a", "sz")]

    try:
        for mkt_name, prefix in markets:
            page = 0
            while True:
                # 腾讯股票列表接口（标准 GBK 纯文本，极快）
                url = f"http://stock.gtimg.cn/data/index.php?appn=rank&t=ranka/chr&p={page}&o=0&l=80&v=list_data"
                r = session.get(url, headers=headers, timeout=6.0)
                if r.status_code == 200 and 'list_data="' in r.text:
                    content = r.text.split('list_data="')[1].split('";')[0].strip()
                    if not content:
                        break
                    items = content.split(",")
                    for it in items:
                        parts = it.split("~")
                        if len(parts) >= 4:
                            cd = parts[1].strip()
                            nm = parts[2].strip()
                            try:
                                px = float(parts[3])
                            except (ValueError, TypeError):
                                px = 0.0
                            all_rows.append({"代码": cd, "名称": nm, "最新价": px})
                    if len(items) < 80:
                        break
                    page += 1
                else:
                    break
                time.sleep(0.05)

        if all_rows:
            df_all = pd.DataFrame(all_rows)
            mask = (
                df_all["代码"].str.startswith(POOL_PREFIX) &
                ~df_all["名称"].str.contains(exclude_pat, na=False) &
                (df_all["最新价"] >= MIN_PRICE)
            )
            pool = df_all[mask][["代码", "名称"]].drop_duplicates(subset=["代码"]).reset_index(drop=True)
    except Exception as e:
        logger.warning(f"腾讯行情列表获取异常: {e}")

    # 方式 2：官方交易所代码表作为保底
    if pool.empty:
        try:
            print("  -> 尝试备用通道: AkShare 交易所基础代码表...")
            df_info = ak.stock_info_a_code_name()
            df_info = df_info.rename(columns={"code": "代码", "name": "名称"})
            mask = (
                df_info["代码"].astype(str).str.startswith(POOL_PREFIX) &
                ~df_info["名称"].astype(str).str.contains(exclude_pat, na=False)
            )
            pool = df_info[mask][["代码", "名称"]].astype(str).drop_duplicates().reset_index(drop=True)
        except Exception as e:
            logger.warning(f"备用通道亦失败: {e}")

    # 3. 持久化缓存至 SQLite
    if not pool.empty:
        storage.save_cached_pool(pool)[cite: 2]
        print(f"✓ 成功获取并持久化全市场股票池至 SQLite: 共 {len(pool)} 只")
    else:
        print("✗ 无法获取全市场股票池，请检查网络连接。")

    if limit and limit > 0:[cite: 2]
        pool = pool.head(limit)[cite: 2]
    return pool[cite: 2]


def main():
    parser = argparse.ArgumentParser(description="A股慢牛与起爆形态智能筛选系统")[cite: 2]
    parser.add_argument("--limit", type=int, default=None, help="快速试跑限制数量")[cite: 2]
    parser.add_argument("--workers", type=int, default=FETCH_WORKERS, help="并发网络线程")[cite: 2]
    parser.add_argument("--min-score", type=int, default=MIN_SCORE, help="综合评分下限")[cite: 2]
    parser.add_argument("--codes", type=str, default=None, help="指定股票代码(逗号隔开)")[cite: 2]
    parser.add_argument("--no-cache", action="store_true", help="禁用 SQLite 缓存")[cite: 2]
    args = parser.parse_args()[cite: 2]

    # 动态获取脚本所在目录，确保在所有操作系统上都是标准相对路径
    base_dir = os.path.dirname(os.path.abspath(__file__))[cite: 2]
    out_dir = os.path.join(base_dir, OUTPUT_SUBDIR)[cite: 2]
    os.makedirs(out_dir, exist_ok=True)[cite: 2]

    db_path = os.path.join(base_dir, CACHE_DB_NAME)[cite: 2]
    storage = SQLiteStorage(db_path)[cite: 2]

    # 快速探测网络连通性
    probe_network()

    # 获取标的池
    pool = get_stock_pool(args.codes, args.limit, storage)
    if pool.empty:
        print("未获取到有效股票标的。程序退出。")
        return

    scanner = StockScanner(args, storage)[cite: 2]
    res_df = scanner.run(pool)[cite: 2]

    if not res_df.empty:[cite: 2]
        stamp = dt.datetime.now().strftime("%Y%m%d_%H%M")[cite: 2]
        csv_file = os.path.join(out_dir, f"选股结果_{stamp}.csv")[cite: 2]
        res_df.to_csv(csv_file, index=False, encoding="utf-8-sig")[cite: 2]
        print(f"\n结果已成功导出至: {csv_file}")[cite: 2]


if __name__ == "__main__":
    main()